// 字典页面
import {DictFormType, DictTableType} from "@/api/sys/admin/dict/types";
import {Ref} from "vue";
import {deleteDictApi, getDictByIdApi, getDictListApi} from "@/api/sys/admin/dict";
import {initPageQuery} from "@/utils/common-fn";
import {openConfirm} from "@/components/MyComponent/XMessageBox";
import {DictOptions} from "@/utils/common-types";
import {commonGetOptions} from "@/utils/format-table";

export const useDictViewStore = defineStore('dictView', () => {

    /**
     * options
     */
        // 状态options
    const statusOptions: Ref<DictOptions[]> = ref([])

    /**
     * table相关
     */
        // 主题
    const title = '书签'
    // table数据
    let tableData: Ref<DictTableType[]> = ref([])
    // 总数
    const total = ref(0)
    // 分页信息,以及查询条件,用于发送api
    const queryData= reactive(initPageQuery<DictTableType>({order: {sort:'asc'}}))
    /**
     * 编辑相关
     */
        // 弹出框:编辑
    const editVisible = ref(false)

    // 编辑的表单数据
    const editForm: Ref<DictFormType> = ref({})


    /**
     * 添加相关
     */
        // 弹出框:编辑
    const addVisible = ref(false)

    // 编辑的表单数据
    const addForm: Ref<DictFormType> = ref({})

    /**
     * 方法相关
     */
    // 设置编辑对话框可见
    function setEditVisible(bolValue: boolean) {
        editVisible.value = bolValue
    }

    // 设置编辑对话框可见
    function setAddVisible(bolValue: boolean) {
        addVisible.value = bolValue
    }

    async function getList() {
        [[tableData.value, total.value], statusOptions.value] = await Promise.all(
            [getDictListApi(queryData),
                ...commonGetOptions('status')]);
    }

    // 打开 编辑
    async function openEdit(id: number) {
        editForm.value = await getDictByIdApi(id)
        editVisible.value = true
    }

    // 删除
    async function openDelete(id: number) {
        if (await openConfirm('确定删除' + title)) {
            await deleteDictApi(id)
            ElMessage.success('删除成功')
            await getList()
        }
    }

    // 打开 添加
    async function openAdd() {
        // 编辑的时候,获取所有的角色
        addForm.value = {
            name: '',
            code: '',
            // 1-正常 0-禁用
            status: 1,
            sort: 1,
            remark: '',
        }
        addVisible.value = true
    }

    return {
        tableData, queryData, total, editVisible, editForm, addForm, addVisible, title,
        statusOptions,
        openEdit, setEditVisible, getList,
        setAddVisible, openAdd, openDelete
    }
})